package cn.sofwin.sb.core.mvc.controller;

import cn.sofwin.sb.core.mvc.entity.IdEntity;
import cn.sofwin.sb.core.mvc.service.BaseService;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 抽象的父类控制器
 * @param <T>
 */
public abstract class BaseController<T extends IdEntity> {

    private BaseService baseService;

    /**
     * 回调函数
     * 通过反射来动态获取注入的service
     * 在抽象的父类中，动态获取子类注入的service对象
     */
    protected BaseService getService(){
        if(baseService==null){
            Field[] fields = this.getClass().getDeclaredFields();
            try {
                cn.sofwin.sb.core.annotation.BaseService bs=null;
                for(Field field:fields){
                    /**获取有BaseService注解的service*/
                    bs=field.getDeclaredAnnotation(cn.sofwin.sb.core.annotation.BaseService.class);
                    if(bs !=null){
                        field.setAccessible(true);
                        baseService= (BaseService) field.get(this);
                        break;
                    }
                }
                if(baseService==null){
                    throw new RuntimeException("为什么不给我提供一个BaseService??????");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return baseService;
    }

    public T find(Integer id){
        return (T)getService().get(id);
    }
}
